package com.a85.wxhelper.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.util.Log;

import java.io.File;

/**
 *
 * @author  hejiangwei
 * @date 2018/7/11
 */
public class DBUtil {
    private volatile static DBUtil single = null;
    private DataBaseDriver mDataBaseDriver;
    private Context mContext;

    private DBUtil(Context context) {
        mContext = context;

    }

    public static DBUtil getInstance(Context context) {
        if (single == null) {
            synchronized (DBUtil.class) {
                if (single == null) {
                    single = new DBUtil(context);
                }
            }
        }
        return single;
    }

    //    public int AddBook(String type_id, List<TextTable> textTableList) {
    /*查看下载的txt文件有没有插入到数据表中*/
    public boolean isHasWords(String type_id) {
        if (!Open()) {
            Close();
            return false;
        }
        String SqlHasWordBook = String.format("select * from tbl_txt where type_id = '%s'", type_id);
        Cursor cursorIsSame = mDataBaseDriver.QuerySQL(SqlHasWordBook);
        if (cursorIsSame.getCount() > 0) {
            return true;
        } else {
            return false;
        }

    }

    public boolean Open() {
        String strSQLContact = "create table if not exists rcontact("
                + "username text primary key,"
                + "alias text,"
                + "conRemark text,"
                + "domainList text,"
                + "nickname text,"
                + "pyInitial text,"
                + "quanPin text,"
                + "showHead text,"
                + "type text)";

        String strSQLMessage = "create table if not exists message("
                + "msgId integer primary key,"
                + "msgSvrId text,"
                + "type integer,"
                + "status integer,"
                + "isSend integer,"
                + "createTime integer,"
                + "talker text,"
                + "content text,"
                + "imgPath text,"
                + "isUpload blob)";

        String strFile = GetFolder(getRoot("/wxhelper/") + "info/") + "base.db";
        Log.e("strFile", strFile);
        mDataBaseDriver = new DataBaseDriver(mContext, strFile);


        boolean bRet = mDataBaseDriver.ExecuteSQL(strSQLContact);
        if (bRet == false) {
            return false;
        }
        bRet = mDataBaseDriver.ExecuteSQL(strSQLMessage);
        if (bRet == false) {
            return false;
        }


        return true;
    }

    public synchronized void Close() {
        mDataBaseDriver.Close();
        mDataBaseDriver=null;
    }

    public static String GetFolder(String strFolder) {
        if (new File(strFolder).exists()) {
            return strFolder;
        }

        new File(strFolder).mkdir();
        return strFolder;
    }

    public static String getRoot(String strRoot) {
        File sdDir = null;
        // 判断sd卡是否存在
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        } else {
            sdDir = Environment.getRootDirectory();
        }

        String strDir = sdDir.toString() + strRoot;
        GetFolder(strDir);
        return strDir;
    }


    /**
     * @return 获取user数量
     */
    public int getUserSize() {
        int result = 0;

//        if (!Open()) {
//            Close();
//            return 0;
//        }
        if (mDataBaseDriver!=null)return -1;
        Open();
        String strSQL = "select count(*) from rcontact";
        Cursor cursor = mDataBaseDriver.QuerySQL(strSQL);
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                result = cursor.getInt(0);
            }
            cursor.close();


            Close();

        }
        return result;
    }


    /**
     * 插入users数据
     * @param cursor hook到的wx的cursor
     */
    public void setUsers(Cursor cursor) {
        if (!Open()) {
            Close();
            return;
        }
        cursor.moveToFirst();
        do {


            String strSQL = "insert into rcontact" +
                    "(username,alias,conRemark,domainList,nickname,pyInitial,quanPin,showHead,type)" +
                    "values(?,?,?,?,?,?,?,?,?)";
            Object[] mValue = new Object[]{
                    cursor.getString(cursor.getColumnIndex("username")),
                    cursor.getString(cursor.getColumnIndex("alias")),
                    cursor.getString(cursor.getColumnIndex("conRemark")),
                    cursor.getString(cursor.getColumnIndex("domainList")),
                    cursor.getString(cursor.getColumnIndex("nickname")),
                    cursor.getString(cursor.getColumnIndex("pyInitial")),
                    cursor.getString(cursor.getColumnIndex("quanPin")),
                    cursor.getString(cursor.getColumnIndex("showHead")),
                    cursor.getString(cursor.getColumnIndex("type")),
            };
            mDataBaseDriver.execSQL(strSQL, mValue);


        } while (cursor.moveToNext());
        cursor.close();
        Close();


    }


    /**
     * 插入user数据
     * @param values hook到的wx的ContentValues
     */
    public void addUser(ContentValues values) {
        if (!Open()) {
            Close();
            return;
        }

            String strSQL = "insert into rcontact" +
                    "(username,alias,conRemark,domainList,nickname,pyInitial,quanPin,showHead,type)" +
                    "values(?,?,?,?,?,?,?,?,?)";
            Object[] mValue = new Object[]{
                    values.get("username"),
                    values.get("alias"),
                            values.get("conRemark"),
                            values.get("domainList"),
                            values.get("nickname"),
                            values.get("pyInitial"),
                            values.get("quanPin"),
                            values.get("showHead"),
                            values.get("type"),
            };
            mDataBaseDriver.execSQL(strSQL, mValue);



        Close();


    }


    /**
     * 清除所有联系人数据
     */
    public void clearUsers() {
        if (!Open()) {
            Close();
            return;
        }
        mDataBaseDriver.ExecuteSQL("delete from rcontact");
        mDataBaseDriver.ExecuteSQL("VACUUM");

        Close();


    }


    /**
     * 更新联系人数据
     * @param values hook到的更新参数
     */
    public void updateUser(ContentValues values) {
        if (!Open()) {
            Close();
            return;
        }

        String updata = String.format("update rcontact set " +
                        "alias = '%s', conRemark = '%s', domainList = '%s', nickname = '%s', " +
                        "pyInitial = '%s', quanPin = '%s', showHead = '%s', type = '%s'," +
                        "where username = '%s'",

                (String)values.get("alias"),
                (String)values.get("conRemark"),
                (String)values.get("domainList"),
                (String)values.get("nickname"),
                (String)values.get("pyInitial"),
                (String)values.get("quanPin"),
                (String)values.get("showHead"),
                (String)values.get("type"),
                (String)values.get("username")
        );

        mDataBaseDriver.ExecuteSQL(updata);


        Close();


    }


    /**
     * @param username wx的id
     * @return 用户昵称
     */
    public String getNickName(String username) {
        String result=null;
        if (!Open()) {
            Close();
            return result;
        }

        String updata = String.format("select * from rcontact where username = '%s'",

                username
        );

        Cursor cursor=mDataBaseDriver.QuerySQL(updata);
        if (cursor!=null) {
        if (cursor.getCount()>0) {
            cursor.moveToFirst();
            result=cursor.getString(cursor.getColumnIndex("nickname"));
        }
         cursor.close();
        }


        Close();

        return result;
    }


    /**
     * 插入消息数据数据
     * @param contentValues hook到的wx的插入数据
     */
    public void insertMsg(ContentValues contentValues) {
        if (!Open()) {
            Close();
            return;
        }

            String strSQL = "insert into message" +
                    "(msgId,msgSvrId,type,status,isSend,createTime,talker,content,imgPath,isUpload)" +
                    "values(?,?,?,?,?,?,?,?,?,?)";
            Object[] mValue = new Object[]{
                            contentValues.get("msgId"),contentValues.get("msgSvrId"),
                            contentValues.get("type"),contentValues.get("status"),
                            contentValues.get("isSend"),contentValues.get("createTime"),
                            contentValues.get("talker"),contentValues.get("content"),
                            contentValues.get("imgPath"),false};
            mDataBaseDriver.execSQL(strSQL, mValue);
        Close();


    }

    /**
     * 更新消息数据
     * @param values hook到的更新参数
     */
    public void updateMessage(String values,int id) {
        if (!Open()) {
            Close();
            return;
        }

        String updata = String.format("update message set " +
                        "msgSvrId = '%s' where msgId = %d", values,id );

        mDataBaseDriver.ExecuteSQL(updata);


        Close();


    }
}
